(function() {
	'use strict';
	var sc = angular.module('sc.login', [])
	var baseUrl = require.toUrl('.') + '../';
	sc.constant('pathPrefix', baseUrl);
	configHttp.$inject = [ '$httpProvider', 'pathPrefix' ]
	function configHttp($httpProvider, pathPrefix) {
		$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
		var param = function(obj) {
			var query = '', name, value, fullSubName, subName, subValue, innerObj, i;
			for (name in obj) {
				value = obj[name];
				if (value instanceof Array) {
					for (i = 0; i < value.length; ++i) {
						subValue = value[i];
						fullSubName = name + '[' + i + ']';
						innerObj = {};
						innerObj[fullSubName] = subValue;
						query += param(innerObj) + '&';
					}
				} else if (value instanceof Object) {
					for (subName in value) {
						subValue = value[subName];
						fullSubName = name + '.' + subName;
						innerObj = {};
						innerObj[fullSubName] = subValue;
						query += param(innerObj) + '&';
					}
				} else if (value !== undefined && value !== null)
					query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
			}
			return query.length ? query.substr(0, query.length - 1) : query;
		}
		$httpProvider.defaults.transformRequest = [ function(data) {
			return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;
		} ]
		var urlReg = /((^\#(\w+)\#)|(^\:(\w+)\:))(.*)/;
		rootPathInterceptor.$inject = [];
		function rootPathInterceptor() {
			var request = function(config) {
				var u = config.url;
				var s = u.charAt(0);
				if (s != '#' && s != ':') {
					return config;
				}
				var r = u.match(urlReg)
				if (r) {
					var p = r[3] || r[5];
					config.url = pathPrefix + r[6];
				}
				return config;
			}
			var requestError = function(c) {
				modalServiceDelegate.error('请求失败', 1000)
				return c;
			}
			return {
				'request' : request,
				'responseError' : requestError
			}
		}
		$httpProvider.interceptors.push(rootPathInterceptor);
	}
	sc.config(configHttp)
	function LoginCtrl($http, pathPrefix) {
		var ctrl = this;
		this.login = function(u, p) {
			ctrl.error = ''
			if (!u) {
				ctrl.error = '请输入用户名'
				return;
			}
			if (!p) {
				ctrl.error = '请输入密码'
				return;
			}
			return $http.post(pathPrefix + 'login/login', {
				username : u,
				password : p
			}).success(function(r) {
				if (r === '') {
					ctrl.error = '用户名或密码错误'
					return;
				}
				if (r != '') {// 登录成功后到index.html
					location.href = (pathPrefix + 'index.html')
				}
				return r;
			});
		}
		this.logout = function() {// 注销成功后到index.html
			return $http.post(pathPrefix + 'login/logout').success(function(r) {
				location.href = (pathPrefix + 'home.html')
			})
		}
	}
	sc.controller('LoginCtrl', LoginCtrl)
})()